package com.mediatecture.flex.component.SaveToPDF
{
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.globalization.NumberFormatter;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	import mx.core.FlexGlobals;
	import mx.resources.IResourceManager;
	import mx.resources.ResourceManager;
	
	import Controller.AreasController;
	import Controller.HeatingController;
	import Controller.QualityController;
	
	import Model.Calculations;
	import Model.HeatRecoverySystem;
	import Model.SolidComponent;
	import Model.SubsoilHeatExchanger;
	import Model.TransparentComponent;
	
	import View.Output.SetupSynopsis;
	import View.shading.ShadingView;
	
	import org.alivepdf.events.PageEvent;
	import org.alivepdf.fonts.CoreFont;
	import org.alivepdf.fonts.FontFamily;
	import org.alivepdf.layout.Mode;
	import org.alivepdf.layout.Orientation;
	import org.alivepdf.layout.Position;
	import org.alivepdf.layout.Resize;
	import org.alivepdf.layout.Size;
	import org.alivepdf.layout.Unit;
	import org.alivepdf.pages.Page;
	import org.alivepdf.pdf.PDF;
	import org.alivepdf.saving.Method;

	public class SaveToPDF extends Sprite
	{
		private var file:File;
		private var pdf:PDF;
		private var resize:Resize;
		private var resize1:Resize;
		
		private var pdfWhiteImg:DisplayObject;
		private var pdfGreyImg:DisplayObject;
		private var header:DisplayObject;
		private var titlePageImage:DisplayObject;
		private var areas:DisplayObject;
		private var opaque:DisplayObject;
		private var windowsdoors:DisplayObject;
		private var certified:DisplayObject;
		private var airtightness:DisplayObject;
		private var thermalBridges:DisplayObject;
		private var tree:DisplayObject;
		private var energyefficiency:DisplayObject;
		
		private var areasController:AreasController;
		private var quantityController:QualityController;
		private var heatingController:HeatingController;
		private var numberFormatter:NumberFormatter;
		
		private var projecDataPage:ArrayCollection;
		private var qualityPage:ArrayCollection;
		private var solidComponentsPages:ArrayCollection;
		private var doorsPages:ArrayCollection;
		private var windowsPages:ArrayCollection;
		private var heatingPage:ArrayCollection;
		private var qualitiAndAirtightnessPage:ArrayCollection;
		private var calculationsPage:ArrayCollection;
		
		private var resourceManager:IResourceManager = ResourceManager.getInstance();
		
		//private var myCoreFont:IFont;
		
		public function SaveToPDF()
		{
			this.projecDataPage = new ArrayCollection();
			this.qualityPage = new ArrayCollection();
			this.solidComponentsPages = new ArrayCollection();
			this.doorsPages = new ArrayCollection();
			this.windowsPages = new ArrayCollection();
			this.heatingPage = new ArrayCollection();
			this.qualitiAndAirtightnessPage = new ArrayCollection();
			this.calculationsPage = new ArrayCollection();
			
			this.areasController = new AreasController();
			this.quantityController = new QualityController();
			this.heatingController = new HeatingController();
			
			//this.myCoreFont = new CoreFont(FontFamily.HELVETICA_BOLD);
				
			this.file = new File();
			this.file = file.resolvePath("/New PDF.pdf");
			this.pdf = new PDF(Orientation.PORTRAIT, Unit.MM, Size.A4);
			file.addEventListener(Event.SELECT, save);
			pdf.addEventListener(PageEvent.ADDED, addHeader);
			this.resize = new Resize(Mode.FIT_TO_PAGE, Position.LEFT);
			this.resize1 = new Resize(Mode.NONE, Position.LEFT);
			
		}
		
		public function startPDF():void
		{
			file.browseForSave("Save as PDF");
			addRowsImages();
		}
		
		private function addRowsImages():void
		{
			var loader:Loader = new Loader();
			loader.load(new URLRequest("img/pdf-white.jpg"));
			
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
			{
				pdfWhiteImg = e.target.loader;
				
				var loader1:Loader = new Loader();
				loader1.load(new URLRequest("img/pdf-grey.jpg"));
				
				loader1.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
				{
					pdfGreyImg = e.target.loader;
					
					var loader2:Loader = new Loader();
					loader2.load(new URLRequest("img/pdf-header.png"));
			
					loader2.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
					{
						header = e.target.loader;
						
						var loader3:Loader = new Loader();
						loader3.load(new URLRequest("img/pdf/coverimage.jpg"));
						
						loader3.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
						{
							titlePageImage = e.target.loader;
							
							var loader4:Loader = new Loader();
							loader4.load(new URLRequest("img/pdf/areas.jpg"));
							
							loader4.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
							{
								areas = e.target.loader;
								
								var loader5:Loader = new Loader();
								loader5.load(new URLRequest("img/pdf/oapque.jpg"));
								
								loader5.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
								{
									opaque = e.target.loader;
									
									var loader6:Loader = new Loader();
									loader6.load(new URLRequest("img/pdf/windowsdoors.jpg"));
									
									loader6.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
									{
										windowsdoors = e.target.loader;
										
										var loader7:Loader = new Loader();
										loader7.load(new URLRequest("img/pdf/certified.jpg"));
										
										loader7.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
										{
											certified = e.target.loader;
											
											var loader8:Loader = new Loader();
											loader8.load(new URLRequest("img/pdf/airtightness.jpg"));
											
											loader8.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
											{
												airtightness = e.target.loader;
												
												var loader9:Loader = new Loader();
												loader9.load(new URLRequest("img/pdf/thermalBridges.jpg"));
												
												loader9.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
												{
													thermalBridges = e.target.loader;
													
													var loader10:Loader = new Loader();
													loader10.load(new URLRequest("img/pdf/tree.jpg"));
													
													loader10.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
													{
														tree = e.target.loader;
														
														startPDFCreation();
													});
												});
											});
										});
									});
								});
							});
						});
					});
				});
			});
		}
		
		private function startPDFCreation():void
		{
			createHeadingPage();
			createProjectDataPage();
			printAreas();
			printSolidComponents();
			printWindows();
			printDoors();
			printQualityAndShading();
			printHVAC();
			printCalculations();
		}
		
		private function newWhiteRow(x:Number, y:Number, strTitle:String, strValue:String):void
		{
			pdf.addImage(pdfWhiteImg, resize1, x, y);
			pdf.setFont(new CoreFont());
			pdf.setFontSize(8);
			pdf.addCell(x,12,"");
			pdf.addCell(70, 12, strTitle);
			pdf.addCell(15, 12, strValue, 0,0,"R");
			pdf.newLine(8);
		}
		
		private function newHeatingDescriptionRow(y:Number, strTitle:String, strValue:String):void
		{
			pdf.addImage(pdfWhiteImg, resize1, 0, y);
			pdf.setFontSize(8);
			pdf.addCell(70, 12, strTitle);
			pdf.addCell(50, 12, strValue);
			pdf.newLine(8);
		}
		
		private function newThreeLabelRow(x:Number, y:Number, strTitle:String, strValue:String, unit:String):void
		{
			pdf.addImage(pdfWhiteImg, resize1, x, y);
			pdf.setFont(new CoreFont());
			pdf.setFontSize(8);
			pdf.addCell(x,12,"");
			pdf.addCell(70, 12, strTitle);
			pdf.addCell(15, 12, strValue, 0,0,"R");
			pdf.addCell(20, 12, unit);
			pdf.newLine(8);
		}
		
		private function newGreyRow(x:Number, y:Number, strTitle:String):void
		{
			pdf.addImage(pdfGreyImg, resize1, x, y);
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			pdf.setFontSize(10);
			pdf.addCell(x,10,"");
			pdf.addCell(x,10,strTitle);
			pdf.newLine(8);
		}
		
		private function newEmptyLine(x:Number, y:Number):void
		{
			pdf.addImage(pdfWhiteImg, resize1, x, y);
			pdf.newLine(8);
		}
		
		private function thermalBridgeYesNo(boo:Boolean):String
		{
			var str:String;
			
			if(boo == true)
			{
				str = "Yes";
			}
			else
			{
				str = "No";
			}
			
			return str;
		}
		
		private function printAreas():void
		{
			
			pdf.addPage();
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.writeText(10, "      HEATED SPACE AREA AND VOLUME");
			pdf.addImage(this.areas,resize1,0,30);
			pdf.newLine(15);
			
			newGreyRow(91, 37, "    Total Heated Space Area");
			newThreeLabelRow(91,44, "    Heated Space Area: ", Number(FlexGlobals.topLevelApplication.getHSA().sum).toFixed(2), " m²");
			newEmptyLine(91,52);
			
			newGreyRow(91,60, "    Total Heated Space Volume");
			newThreeLabelRow(91,68, "    Heated Space Volume: ", Number(FlexGlobals.topLevelApplication.getHSVArea()).toFixed(2), " m³");
			newEmptyLine(91,76);
			
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.newLine(10);
			
			pdf.writeText(10, "         ENVELOPE- OPAQUE ELEMENTS");
			pdf.newLine(7);
			
			pdf.addImage(this.opaque,resize1,0,118);
			
			newGreyRow(91,110, "    Average U-Values");
			newWhiteRow(91, 118, "    Pitched Roof/Mono Pitched", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','roofAreaSloped')))+ " W/(m²K)");
			newWhiteRow(91, 126, "    Flat Roof", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','roofAreaFlat')))+ " W/(m²K)");
			newWhiteRow(91,134, "    Wall against air: ",returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','exteriorWallToAmbientAir')))+ " W/(m²K)");
			newWhiteRow(91,142, "    Wall against ground: ", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','exteriorWallToGround')))+ " W/(m²K)");
			newWhiteRow(91,150, "    Wall against neighbour: ", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','externalWallPartitionWall')))+ " W/(m²K)");
			newWhiteRow(91,158, "    Wall against unheated cellar: ", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','externalWallToCellar')))+ " W/(m²K)");
			newWhiteRow(91,166, "    Slab against ground: ",returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','groundSlab')))+ " W/(m²K)");
			newWhiteRow(91,174, "    Slab against unheated cellar: ", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfSolidComponentsByType(resourceManager.getString('systemtexts','groundSlabAgainstCellar')))+ " W/(m²K)");
			
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.newLine(1);
			
			pdf.writeText(10, "         ENVELOPE- WINDOWS AND DOORS");
			
			pdf.newLine(29);
			
			pdf.addImage(this.windowsdoors,resize1,0,203);
			
			newGreyRow(91,219, "    Average U-Values");
			newWhiteRow(91, 227, "    Windows", returnDashIfNumberIsZero(this.areasController.calculateMeanUValueOfWindows())+ " W/(m²K)");
			newWhiteRow(91,235, "    Doors: ", returnDashIfNumberIsZero(this.areasController.calculateMeanUvalueDoors())+ " W/(m²K)");
			
			for(var i:Number = 0; i < pdf.getPages().length; i++)
			{
				this.qualityPage.addItem(pdf.getPage(i + 1));
			}
			pdf.removeAllPages();
		}
		
		private function returnDashIfNumberIsZero(number:Number):String
		{
			if(isNaN(number) || number == 0)
				return "----  ";
			return number.toFixed(2);
		}
		
		private function printSC(desc:String, imgPath:String, id:String, length:String, height:String, area:String, name:String, uValue:Number, dimensions:String, cutName:String, layers:String):void
		{
			var loader:Loader = new Loader();
			addChild(loader);
			
			loader.load(new URLRequest(imgPath));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
			{
				pdf.addPage();
				
				pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
				
				pdf.setFontSize(10);
				pdf.writeText(10, "AREAS");
				pdf.newLine(8);
				pdf.writeText(10, "Solid Components");
				pdf.newLine(11);
				
				newGreyRow(0,40, "    " + desc);
				newWhiteRow(0,48, "    ID: ", id);
				newThreeLabelRow(0,56, "    Length: ", length," m");
				newThreeLabelRow(0,64, "    Height: ", height, " m");
				newThreeLabelRow(0,72, "    Area: ", area, " m²");
				newThreeLabelRow(0,80, "    U-Value:",uValue.toFixed(2) , " W/(m²K)");
				newWhiteRow(0,88, "    ", "");
				newWhiteRow(0,96, "    ", "");
				newWhiteRow(0,104, "    ", "");
				newWhiteRow(0,112, "    ", "");
				newWhiteRow(0,120, "    ", "");
				newWhiteRow(0,128, "    ", "");
				newWhiteRow(0,136, "    ", "");
				newWhiteRow(0,144, "    ", "");
				newWhiteRow(0,152, "    ", "");
				newWhiteRow(0,160, "    ", "");
				newWhiteRow(0,168, "    ", "");
				
				pdf.addImage(e.target.loader, resize1, 10, 96);
				if(FlexGlobals.topLevelApplication.project.areas.selectedSystem != "IC")
				{
					pdf.addImage(certified,resize1, 90,100);
				}
				
				newGreyRow(0,176, "    " + cutName+" Info");
				
				pdf.setFont(new CoreFont());
				pdf.setFontSize(8);
				pdf.newLine(-64);
				newEmptyLine(0,184);
				newEmptyLine(0,192);
				newEmptyLine(0,200);
				newEmptyLine(0,208);
				newEmptyLine(0,216);
				newEmptyLine(0,224);
				newEmptyLine(0,232);
				newEmptyLine(0,240);
				newEmptyLine(0,248);
				
				var pattern:RegExp = /<br>/g;
				var returns:RegExp = /\r\n/g;
				
				dimensions = dimensions.replace(returns, "");
				layers = layers.replace(returns, "");
				
				dimensions = dimensions.replace(pattern, "hui");
				layers = layers.replace(pattern, "hui");
				
				var arrD:Array = new Array();
				var arrN:Array = new Array();
				
				arrD = dimensions.split("hui");
				arrN = layers.split("hui");
				
				var obj:Object;
				
				var arrayWithDimensions:Array = new Array();
				var arrayWithNames:Array = new Array();
				
				var j:Number = 0;
				var k:Number = 0;
				
				for each(var str:String in arrD)
				{	
					obj = new Object();
					
					obj.index = j;
					obj.dimensions = str;
					
					arrayWithDimensions.push(obj);
					
					j++;
				}
				
				for each(var str:String in arrN)
				{
					obj = new Object();
					
					obj.index = k;
					obj.names = str;
					
					arrayWithNames.push(obj);
					
					k++
				}
				
				for each(var dimension:Object in arrayWithDimensions)
				{
					var index:Number = dimension.index;
					pdf.addCell(20, 5, "    " + dimension.dimensions);
					
					for each(var name:Object in arrayWithNames)
					{
						if(index == name.index)
						{
							pdf.addCell(100, 5, name.names);
						}
					}
					pdf.newLine(5);
				}
			
				
				for(var i:Number = 0; i < pdf.getPages().length; i++)
				{
					solidComponentsPages.addItem(pdf.getPage(i + 1));
				}
				
				pdf.removeAllPages();

			});
		}
		
		private function printWin(desc:String, imgPath:String, id:String, length:String, height:String, area:String, name:String,uValue:Number, dimensions:String, cutName:String, layers:String):void
		{
			var loader:Loader = new Loader();
			addChild(loader);
			
			loader.load(new URLRequest(imgPath));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
			{
				pdf.addPage();
				
				pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
					
				pdf.setFontSize(10);
				pdf.writeText(10, "AREAS");
				pdf.newLine(8);
				pdf.writeText(10, "Transparent Components");
				pdf.newLine(11);
					
				newGreyRow(0,40, "    " + desc);
				newWhiteRow(0,48, "    ID: ", id);
				newThreeLabelRow(0,56, "    Length: ", length, " m");
				newThreeLabelRow(0,64, "    Height: ", height, " m");
				newThreeLabelRow(0,72, "    Area: ", area, " m²");
				newThreeLabelRow(0,80, "    U-Value: ", uValue.toFixed(2),  " W/(m²K)");
				newEmptyLine(0,88);
				newEmptyLine(0,96);
				newEmptyLine(0,104);
				newEmptyLine(0,112);
				newEmptyLine(0,120);
				newEmptyLine(0,128);
				newEmptyLine(0,136);
				newEmptyLine(0,144);
				newEmptyLine(0,152);
				newEmptyLine(0,160);
					
				pdf.addImage(e.target.loader, resize1, 10, 96);
				if(FlexGlobals.topLevelApplication.project.areas.selectedSystem != "IC")
				{
					pdf.addImage(certified,resize1, 90,100);
				}
				
				newGreyRow(0,168, "    " + cutName+" Info");
				
				pdf.setFont(new CoreFont());
				pdf.setFontSize(8);
				pdf.newLine(-64);
				newEmptyLine(0,176);
				newEmptyLine(0,184);
				newEmptyLine(0,192);
				newEmptyLine(0,200);
				newEmptyLine(0,208);
				newEmptyLine(0,216);
				newEmptyLine(0,224);
				newEmptyLine(0,232);
				newEmptyLine(0,240);
				
				
				var pattern:RegExp = /<br>/g;
				var returns:RegExp = /\r\n/g;
				
				dimensions = dimensions.replace(returns, "");
				layers = layers.replace(returns, "");
				
				dimensions = dimensions.replace(pattern, "hui");
				layers = layers.replace(pattern, "hui");
				
				var arrD:Array = new Array();
				var arrN:Array = new Array();
				
				arrD = dimensions.split("hui");
				arrN = layers.split("hui");
				
				var obj:Object;
				
				var arrayWithDimensions:Array = new Array();
				var arrayWithNames:Array = new Array();
				
				var j:Number = 0;
				var k:Number = 0;
				
				for each(var str:String in arrD)
				{	
					obj = new Object();
					
					obj.index = j;
					obj.dimensions = str;
					
					arrayWithDimensions.push(obj);
					
					j++;
				}
				
				for each(var str:String in arrN)
				{
					obj = new Object();
					
					obj.index = k;
					obj.names = str;
					
					arrayWithNames.push(obj);
					
					k++
				}
				
				for each(var dimension:Object in arrayWithDimensions)
				{
					var index:Number = dimension.index;
					
					pdf.addCell(20, 5, "    " + dimension.dimensions);
					
					for each(var name:Object in arrayWithNames)
					{
						if(index == name.index)
						{
							pdf.addCell(100, 5, name.names);
						}
					}
					pdf.newLine(5);
				}
				
				for(var i:Number = 0; i < pdf.getPages().length; i++)
				{
					windowsPages.addItem(pdf.getPage(i + 1));
				}
				
				pdf.removeAllPages();
			});
		}
		
		private function printDoor(desc:String, imgPath:String, id:String, length:String, height:String, area:String, name:String,uValue:Number, dimensions:String, cutName:String, layers:String):void
		{
			var loader:Loader = new Loader();
			addChild(loader);
			
			loader.load(new URLRequest(imgPath));
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
			{
				pdf.addPage();
				
				pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
				
				pdf.setFontSize(10);
				pdf.writeText(10, "AREAS");
				pdf.newLine(8);
				pdf.writeText(10, "Transparent Components");
				pdf.newLine(11);
				
				newGreyRow(0,40, "    " + desc);
				newWhiteRow(0,48, "    ID: ", id);
				newThreeLabelRow(0,56, "    Length: ", length, " m");
				newThreeLabelRow(0,64, "    Height: ", height, " m");
				newThreeLabelRow(0,72, "    Area:", area, " m²");
				newThreeLabelRow(0,80, "    U-Value:", uValue.toFixed(2), " W/(m²K)");
				newEmptyLine(0,88);
				newEmptyLine(0,96);
				newEmptyLine(0,104);
				newEmptyLine(0,112);
				newEmptyLine(0,120);
				newEmptyLine(0,128);
				newEmptyLine(0,136);
				newEmptyLine(0,144);
				newEmptyLine(0,152);
				newEmptyLine(0,160);
				
				pdf.addImage(e.target.loader, resize1, 10, 96);
				if(FlexGlobals.topLevelApplication.project.areas.selectedSystem != "IC")
				{
					pdf.addImage(certified,resize1, 90,100);
				}
				
				newGreyRow(0,168, "    " + cutName+" Info");
				
				pdf.setFont(new CoreFont());
				pdf.setFontSize(8);
				pdf.newLine(-64);
				newEmptyLine(0,176);
				newEmptyLine(0,184);
				newEmptyLine(0,192);
				newEmptyLine(0,200);
				newEmptyLine(0,208);
				newEmptyLine(0,216);
				newEmptyLine(0,224);
				newEmptyLine(0,232);
				newEmptyLine(0,240);
				
				var pattern:RegExp = /<br>/g;
				var returns:RegExp = /\r\n/g;
				
				dimensions = dimensions.replace(returns, "");
				layers = layers.replace(returns, "");
				
				dimensions = dimensions.replace(pattern, "hui");
				layers = layers.replace(pattern, "hui");
				
				var arrD:Array = new Array();
				var arrN:Array = new Array();
				
				arrD = dimensions.split("hui");
				arrN = layers.split("hui");
				
				var obj:Object;
				
				var arrayWithDimensions:Array = new Array();
				var arrayWithNames:Array = new Array();
				
				var j:Number = 0;
				var k:Number = 0;
				
				for each(var str:String in arrD)
				{	
					obj = new Object();
					
					obj.index = j;
					obj.dimensions = str;
					
					arrayWithDimensions.push(obj);
					
					j++;
				}
				
				for each(var str:String in arrN)
				{
					obj = new Object();
					
					obj.index = k;
					obj.names = str;
					
					arrayWithNames.push(obj);
					
					k++
				}
				
				for each(var dimension:Object in arrayWithDimensions)
				{
					var index:Number = dimension.index;
					
					pdf.addCell(20, 5, "    " + dimension.dimensions);
					
					for each(var name:Object in arrayWithNames)
					{
						if(index == name.index)
						{
							pdf.addCell(100, 5, name.names);
						}
					}
					pdf.newLine(5);
				}
				
				for(var i:Number = 0; i < pdf.getPages().length; i++)
				{
					doorsPages.addItem(pdf.getPage(i + 1));
				}
				
				pdf.removeAllPages();
			});
		}
		
		private function printQualityAndShading():void
		{
			pdf.addPage();
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.writeText(10, "                              QUALITY");
			pdf.addImage(airtightness,resize1,0,30);
			pdf.newLine(15);
			
			newGreyRow(91, 37, "    Airtightness");
			newThreeLabelRow(91,44, "    Airtightness rate: ", this.quantityController.getAirtightnessRate().toFixed(2), "");
			newEmptyLine(91, 52);
			pdf.newLine(16);
			//newGreyRow(91,60, "    Total Heated Space Volume");
			//newThreeLabelRow(91,68, "    Heated Space Volume: ", Number(FlexGlobals.topLevelApplication.getHSVArea()).toFixed(2), " m³");
			//newEmptyLine(91,76);
			
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.newLine(20);
			
			pdf.writeText(10, "                              QUALITY");
			pdf.newLine(18);
			
			pdf.addImage(thermalBridges,resize1,0,114);
			
			newGreyRow(91,123, "    Thermal Bridges");
			newWhiteRow(91, 131, "    Thermal Bridge Free:", thermalBridgeYesNo(this.quantityController.getThermalBridgeFree()));
			newEmptyLine(91,139);
			
			pdf.newLine(31);
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.newLine(13);
			
			pdf.writeText(10, "                              SHADING");
			
			pdf.newLine(20);
			
			pdf.addImage(tree,resize1,0,203);
			
			newGreyRow(91,210, "    Mean Shading Factors");
			newWhiteRow(91, 218, "    North", ((FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromBalconies.shadingNorth.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromNeighbouringHouses.shadingNorth.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromTrees.shadingNorth.shadingFactor).toFixed(2) + "");
			newWhiteRow(91,226, "    East: ", ((FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromBalconies.shadingEast.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromNeighbouringHouses.shadingEast.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromTrees.shadingEast.shadingFactor).toFixed(2)+ "");
			newWhiteRow(91,234, "    South: ",((FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromBalconies.shadingSouth.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromNeighbouringHouses.shadingSouth.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromTrees.shadingSouth.shadingFactor).toFixed(2)+ "");
			newWhiteRow(91,242, "    West: ", ((FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromBalconies.shadingWest.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromNeighbouringHouses.shadingWest.shadingFactor * 
				(FlexGlobals.topLevelApplication.screenCollection[7] as ShadingView).shadingFromTrees.shadingWest.shadingFactor).toFixed(2)+ "");
			newEmptyLine(91,250);
			
			for(var i:Number = 0; i < pdf.getPages().length; i++)
			{
				this.qualitiAndAirtightnessPage.addItem(pdf.getPage(i + 1));
			}
			pdf.removeAllPages();
		}
		
		private function printHVAC():void
		{
			var heatRecoverySystem:HeatRecoverySystem = this.heatingController.getHeatRecoverySystem();
			var subsoilHeatExchanger:SubsoilHeatExchanger = this.heatingController.getSubsoilHeatExchanger();
			
			if(heatRecoverySystem.efficiency != 0)
			{
				var loader:Loader = new Loader();
				addChild(loader);
				
				loader.load(new URLRequest(heatRecoverySystem.pictureURL));
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
				{
					pdf.addPage();
					
					pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
						
					pdf.setFontSize(10);
					pdf.writeText(10, "HVAC");
					pdf.newLine(10);
					
					newGreyRow(0,30,  "    System Performance");
					newEmptyLine(0,38);
					newWhiteRow(0,46, "    Heat Recovery System: ", heatRecoverySystem.efficiency.toFixed(2) + " %");
					newWhiteRow(0,54, "    Subsoil Heat Exchanger: ", subsoilHeatExchanger.efficiency.toFixed(2) + " %");
					newEmptyLine(0,62);
					newEmptyLine(0,70);
					newGreyRow(0,78, "    HVAC System");
					newEmptyLine(0,86);
					newEmptyLine(0,94);
					newEmptyLine(0,102);
					newEmptyLine(0,110);
					newEmptyLine(0,118);
					newEmptyLine(0,126);
					newEmptyLine(0,134);
					newEmptyLine(0,142);
					newEmptyLine(0,150);
					newEmptyLine(0,158);
						
					pdf.addImage(e.target.loader, resize1, 10, 86);
	
					if(!isNaN(subsoilHeatExchanger.efficiency))
					{
						newGreyRow(0,166, "    Subsoil Heat Exchanger");
						newEmptyLine(0,174);
						newThreeLabelRow(0,182, "    Length: ", subsoilHeatExchanger.length.toString(), " m");
						newThreeLabelRow(0,190, "    Efficiency: ", subsoilHeatExchanger.efficiency.toString(), " %");
						newEmptyLine(0,198);
						newEmptyLine(0,206);
					}
					for(var i:Number = 0; i < pdf.getPages().length; i++)
					{
						heatingPage.addItem(pdf.getPage(i + 1));
					}
					
					pdf.removeAllPages();
				});
			}
		}
		
		private function printCalculations():void
		{
			var calculations:Calculations = FlexGlobals.topLevelApplication.calculations;
			
			var loader:Loader = new Loader();
			
			if(calculations.specificAnnualHeatDemand<=10)
			{
				loader.load(new URLRequest("img/pdf/energyeff1.jpg"));
			}
			else if(calculations.specificAnnualHeatDemand<=15)
			{
				loader.load(new URLRequest("img/pdf/energyeff2.jpg"));
			} 
			else if(calculations.specificAnnualHeatDemand<=25)
			{
				loader.load(new URLRequest("img/pdf/energyeff3.jpg"));
			}
			else if(calculations.specificAnnualHeatDemand<=50)
			{
				loader.load(new URLRequest("img/pdf/energyeff4.jpg"));
			}
			else if(calculations.specificAnnualHeatDemand<=100)
			{
				loader.load(new URLRequest("img/pdf/energyeff5.jpg"));
			}
			else if(calculations.specificAnnualHeatDemand<=150)
			{
				loader.load(new URLRequest("img/pdf/energyeff6.jpg"));
			}
			else if(calculations.specificAnnualHeatDemand<=200)
			{
				loader.load(new URLRequest("img/pdf/energyeff7.jpg"));
			}
			else if(calculations.specificAnnualHeatDemand<=250)
			{
				loader.load(new URLRequest("img/pdf/energyeff8.jpg"));
			}
			
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function f(e:Event):void
			{
				energyefficiency = e.target.loader;
				
				pdf.addPage();
				
				pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
				
				pdf.setFontSize(10);
				pdf.writeText(10, "CALCULATIONS");
				pdf.newLine(10);
				
				newGreyRow(0,30, "    Calculations");
				newThreeLabelRow(0,38, "    Transmission Heat Losses: ", calculations.transmissionHeatLosses.toFixed(2), " kWh/a");
				newThreeLabelRow(0,46, "    Ventilation Heat Losses: ", calculations.ventilationHeatLosses.toFixed(2), " kWh/a");
				newThreeLabelRow(0,54, "    Total Heat Losses: ", calculations.totalHeatLosses.toFixed(2), " kWh/a");
				newThreeLabelRow(0,62, "    Internal Heat Gains: ", calculations.internalHeatGains.toFixed(2), " kWh/a");
				newThreeLabelRow(0,70, "    Available Solar Heat Gains: ", calculations.solarHeatGains.toFixed(2), " kWh/a");
				newThreeLabelRow(0,78, "    Total Heat Gains: ", calculations.totalHeatGains.toFixed(2), " kWh/a");
				newThreeLabelRow(0,86, "    Annual Heat Demand: ", calculations.annualHeatDemand.toFixed(2), " kWh/a");
				newThreeLabelRow(0,94, "    Specific Annual Heat Demand: ", calculations.specificAnnualHeatDemand.toFixed(2), " kWh/(m²a)");
				newEmptyLine(0,102);
				
				pdf.addImage(energyefficiency,resize1,0, 120);
				
				
				for(var i:Number = 0; i < pdf.getPages().length; i++)
				{
					calculationsPage.addItem(pdf.getPage(i + 1));
				}
				
				pdf.removeAllPages();
				
			});
		}
		
		private function printSolidComponents():void
		{
			for each(var solidcomponent:SolidComponent in this.areasController.getAllSolidComponentsWithAttachedConstruction())
			{
				printSC(solidcomponent.description, solidcomponent.construction.imageURL, solidcomponent.id, solidcomponent.length.toFixed(2), solidcomponent.height.toFixed(2),
							solidcomponent.area.toFixed(2), solidcomponent.construction.name, solidcomponent.construction.uValue,
							solidcomponent.construction.cutInfo.dimensions, solidcomponent.construction.cutInfo.cutName  ,solidcomponent.construction.cutInfo.layersNames);
			}
		}
		
		private function printWindows():void
		{
			for each(var window:TransparentComponent in this.areasController.getWindowsWithAttachedConstruction())
			{
				printWin(window.description, window.construction.imageURL, window.id, window.length.toFixed(2),
							window.height.toFixed(2), window.area.toFixed(2), window.construction.name, window.construction.uValue,
							window.construction.cutInfo.dimensions, window.construction.cutInfo.cutName ,window.construction.cutInfo.layersNames);
			}
		}
		
		private function printDoors():void
		{
			for each(var door:TransparentComponent in this.areasController.getDoorsWithAttachedConstruction())
			{
				printDoor(door.description, door.construction.imageURL, door.id, door.length.toFixed(2),
					door.height.toFixed(2), door.area.toFixed(2), door.construction.name, door.construction.uValue, 
					door.construction.cutInfo.dimensions, door.construction.cutInfo.cutName ,door.construction.cutInfo.layersNames);
			}
		}
		
		private function createHeadingPage():void
		{
			pdf.addPage();
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			pdf.setFontSize(18);
			pdf.newLine(20);
			pdf.addCell(170,10,"Performance Simulation",0,0,"C");
			pdf.newLine(10);
			pdf.addCell(170,10,FlexGlobals.topLevelApplication.project.projectInfo.object.name,0,0,"C");
			pdf.addImage(this.titlePageImage,resize1,5,70);
			pdf.setFontSize(12);
			pdf.addCell(170,10,FlexGlobals.topLevelApplication.project.projectInfo.object.name + ", " + 
				FlexGlobals.topLevelApplication.project.projectInfo.object.address.street + ", " +
				FlexGlobals.topLevelApplication.project.projectInfo.object.address.town + ", " +
				FlexGlobals.topLevelApplication.project.projectInfo.object.address.country + ", ",0,0,"C");
			pdf.newLine(170);
			pdf.newLine(15);
			pdf.addCell(50,10,"");
			pdf.addCell(30,10,"Owner:",0,0,"L");
			pdf.addCell(5,10,"");
			pdf.addCell(30,10, FlexGlobals.topLevelApplication.project.projectInfo.builder.name,0,0,"L");
			pdf.newLine(5);
			pdf.addCell(50,10,"");
			pdf.addCell(30,10,"Architect:",0,0,"L");
			pdf.addCell(5,10,"");
			pdf.addCell(30,10, FlexGlobals.topLevelApplication.project.projectInfo.architect.name,0,0,"L");
			
			for(var i:Number = 0; i < pdf.getPages().length; i++)
			{
				projecDataPage.addItem(pdf.getPage(i + 1));
			}
			pdf.removeAllPages();
			
		}
		
		private function createProjectDataPage():void
		{
			pdf.addPage();

			pdf.setLeftMargin(20);
			pdf.setRightMargin(20);
			
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.setFontSize(10);
			pdf.writeText(10, "PROJECT DATA");
			
			pdf.newLine(10);
			
			pdf.addImage(pdfGreyImg, resize1, 0, 30);
			
			//Subtitle
			pdf.setFontSize(10);
			pdf.writeText(10, "    Addresses");
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont());
			
			//Object data
			pdf.setFontSize(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 39);
			pdf.addCell(70, 12, "    Object: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.object.name);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 47);
			pdf.addCell(70, 12, "    Street: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.object.address.street);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 55);
			pdf.addCell(70, 12, "    ZIP/Town: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.object.address.town);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 63);
			pdf.addCell(70, 12, "    Country: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.object.address.country);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 71);
			pdf.newLine(8);
			
			//Builder data
			pdf.addImage(pdfWhiteImg, resize1, 0, 79);
			pdf.addCell(70, 12, "    Builder: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.builder.name);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 87);
			pdf.addCell(70, 12, "    Street: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.builder.address.street);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 95);
			pdf.addCell(70, 12, "    ZIP/Town: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.builder.address.town);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 103);
			pdf.addCell(70, 12, "    Country: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.builder.address.country);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 111);
			pdf.newLine(8);
			
			//Architect data
			pdf.addImage(pdfWhiteImg, resize1, 0, 119);
			pdf.addCell(70, 12, "    Architect: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.architect.name);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 127);
			pdf.addCell(70, 12, "    Street: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.architect.address.street);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 135);
			pdf.addCell(70, 12, "    ZIP/Town: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.architect.address.town);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 143);
			pdf.addCell(70, 12, "    Country: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.architect.address.country);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 151);
			pdf.addCell(70, 12, "    Notes: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.notes);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 159);
			pdf.newLine(8);
			
			//Climate data
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.addImage(pdfGreyImg, resize1, 0, 167);
			pdf.setFontSize(10);
			pdf.writeText(10, "    Climate");
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont());
			
			pdf.addImage(pdfWhiteImg, resize1, 0, 175);
			pdf.setFontSize(8);
			pdf.addCell(70, 12, "    Climate zone: ");
			if(FlexGlobals.topLevelApplication.project.projectInfo.climateZone.label != null)
			{
				pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.climateZone.label);
			}
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 183);
			pdf.newLine(8);
			
			//Construction data
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.addImage(pdfGreyImg, resize1, 0, 191);
			pdf.setFontSize(10);
			pdf.writeText(10, "    Type of Construction");
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont());
			
			pdf.addImage(pdfWhiteImg, resize1, 0, 199);
			pdf.setFontSize(8);
			pdf.addCell(70, 12, "    Construction: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.typeConstruction);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 207);
			pdf.newLine(8);
			
			//Usage data
			pdf.setFont(new CoreFont(FontFamily.HELVETICA_BOLD));
			
			pdf.addImage(pdfGreyImg, resize1, 0, 215);
			pdf.setFontSize(10);
			pdf.writeText(10, "    Usage");
			pdf.newLine(8);
			
			pdf.setFont(new CoreFont());
			
			pdf.addImage(pdfWhiteImg, resize1, 0, 223);
			pdf.setFontSize(8);
			pdf.addCell(70, 12, "    Building type: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.buildingType);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 231);
			pdf.addCell(70, 12, "    Usage: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.usage);
			pdf.newLine(8);
			pdf.addImage(pdfWhiteImg, resize1, 0, 239);
			pdf.addCell(70, 12, "    Interior temp.: ");
			pdf.addCell(70, 12, FlexGlobals.topLevelApplication.project.projectInfo.interiorTemperature + "°");
			pdf.newLine(8);
			
			for(var i:Number = 0; i < pdf.getPages().length; i++)
			{
				projecDataPage.addItem(pdf.getPage(i + 1));
			}
			pdf.removeAllPages();
		}
		
		protected function save(event:Event):void
		{
			var f:FileStream = new FileStream();
			f.open(file, FileMode.WRITE);
			
			var synopsisSettings:SetupSynopsis = FlexGlobals.topLevelApplication.setupSynopsis;
			
			if(synopsisSettings.projectDataChkBox.selected == true)
			{
				for each(var page:Page in this.projecDataPage)
				{
					pdf.addPage(page);	
				}
			}
			if(synopsisSettings.areasChkBox.selected == true)
			{	
				for each(var page:Page in this.qualityPage)
				{
					pdf.addPage(page);	
				}
			}
			if(synopsisSettings.solidComponentsChkBox.selected == true)
			{	
				for each(var page:Page in this.solidComponentsPages)
				{
					pdf.addPage(page);	
				}
			}
			if(synopsisSettings.windowsChkBox.selected == true)
			{
				for each(var page:Page in this.windowsPages)
				{
					pdf.addPage(page);	
				}
			}
			if(synopsisSettings.doorsChkBox.selected == true)
			{
				for each(var page:Page in this.doorsPages)
				{
					pdf.addPage(page);	
				}
			}
			
			for each(var page:Page in this.qualitiAndAirtightnessPage)
			{
				pdf.addPage(page);
			}
			
			if(synopsisSettings.heatingChkBox.selected == true)
			{
				for each(var page:Page in this.heatingPage)
				{
					pdf.addPage(page);	
				}
			}
			if(synopsisSettings.calculationsChkBox.selected == true)
			{
				for each(var page:Page in this.calculationsPage)
				{
					pdf.addPage(page);	
				}
			}
			var bytes:ByteArray = pdf.save(Method.LOCAL);
			f.writeBytes(bytes);
			f.close();
		}
		
		protected function addHeader(event:PageEvent):void
		{
			pdf.setLeftMargin(0);
			pdf.setRightMargin(0);
			pdf.addImage(header, resize);
			pdf.newLine(20);
			pdf.setLeftMargin(20);
		}
	}
}